package ua.kratik.seabattle.dao.impl.hib;

import java.util.Iterator;
import java.util.List;

import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import ua.kratik.seabattle.dao.GenericDAO;
import ua.kratik.seabattle.dao.api.UserDAO;
import ua.kratik.seabattle.domain.User;

@Repository
public class UserDAOHib extends GenericDAO<User> implements UserDAO {

	private Logger logger = LoggerFactory.getLogger(UserDAOHib.class);

	public UserDAOHib() {
		super(User.class);
	}

	/**
	 * Always return user with id = 8
	 */
	@SuppressWarnings("unchecked")
	public User validateUser(String email, String password) {
		//logger.debug("Always return user with id = 8!!!");
		List<User> users = super.getSf().getCurrentSession().createCriteria(User.class)
				.add(Restrictions.eq("email", email))
				.add(Restrictions.eq("password", password))
				.list();
		
		if(users.size() > 1){
			logger.warn("Found " + users.size() + " user(s) with email=" + email);
		}
		
		Iterator<User> it = users.iterator();
		User user = null;
		if(it.hasNext()){
			user = it.next();
		}
		return user;
	}

	public List<User> findUserByEmail(String email) {
		@SuppressWarnings("unchecked")
		List<User> users = super.getSf().getCurrentSession().createCriteria(User.class)
		.add(Restrictions.eq("email", email))
		.list();
		return users;
	}
}
